﻿// See https://aka.ms/new-console-template for more information



using Max.PH6_2009A.LowCode.Common;
using Max.PH6_2009A.LowCode.Domain;
using System.Data;

//var u = new UserModel() { Password = "" };
//var s = ReflecationHelper.GetDapperUpdateSqlString(u);
//Console.WriteLine(s);


string card = "12afdasfasfjafja;dfasjfaf;afdkasf345678910";
int len = 6;
var newcard = card.Substring(card.Length - len, len);
Console.WriteLine( newcard);

#region table to list

//DataTable dt = new DataTable();
//dt.Columns.Add(new DataColumn("Password"));
//dt.Columns.Add(new DataColumn("LoginName"));

//for (int i = 1; i <= 10; i++)
//{
//    DataRow dr = dt.NewRow();
//    dr["Password"] = Guid.NewGuid();
//    dr["LoginName"] = $"loginname{i.ToString()}";
//    dt.Rows.Add(dr);
//}
//var list = ReflecationHelper.DatatableToList<UserModel>(dt);


//List<UserModel> users = new List<UserModel>();
//users.Add(new UserModel { Id = new Guid(), LoginName="lcg" });
//users.Add(new UserModel { Id = new Guid(), LoginName = "max" });

//var dt = ReflecationHelper.ListToDatatable(users);

#endregion

Console.ReadKey();

#region 反射
/*
 * 反射是一种技术，可以动态获取程序集中的对象（包括：类、接口、成品、属性、字段、方法。。。）
 * **/

/*
 * 反射的使用
 * System.Reflection
 * System.Type
 * **/
//System.Reflection.Assembly.Load("");//相对路径  a.dll
//System.Reflection.Assembly.LoadFile("");//绝对路么  C:\inetpub\custerr\zh-CN\a.dll
//System.Reflection.Assembly.LoadFrom("");//可相可绝

void CreateInsertSql()
{
    UserModel user = new UserModel();

    var t = user.GetType(); //typeof(UserModel);

    string sql = $"insert into 表名(字段名1,字段名2) values('字段值1','字段值2')";
    //在dapper里，sql怎么写
    sql = $"insert into 表名(字段名1,字段名2) values(@字段名1，@字段名2)";
    string tableName = "";
    string filedName = "";
    string fileValue = "";

    var obj = t.GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.Schema.TableAttribute), true);

    if (obj != null && obj.Length > 0)
    {
        tableName = ((System.ComponentModel.DataAnnotations.Schema.TableAttribute)obj[0]).Name;
    }
    else
    {
        tableName = t.Name;
    }

    var ps = t.GetProperties();
    ps.ToList().ForEach(p =>
    {
        if (!p.Name.ToLower().Equals("id"))
        {

            //根据值不会空的情况下，才能放到sql里面
            //如何获取它的值？
            var v =p.GetValue(user);
            if(v != null)
            {
                filedName += p.Name + ",";
                fileValue += $"@{p.Name},";

                //if (v.GetType() != typeof(int))
                //{
                //    filedName += p.Name + ",";
                //    fileValue += $"@{p.Name},";
                //}
                //else if(((int)v)!=0)
                //{
                //    filedName += p.Name + ",";
                //    fileValue += $"@{p.Name},";
                //}
            }
        }
    });
    sql = $"insert into {tableName}({filedName.TrimEnd(',')}) values({fileValue.TrimEnd(',')})";
    Console.WriteLine(sql);
}
void CreateUpdateSql<TEntity>(TEntity entity)
{

    string sql = "update 表名　 set 字段名1=字段值1,字段名2=字段值2 where id=id";
    var t = entity.GetType();

    string tableName = "";
    string filedValue = "";
    string id = "";
    sql = "update 表名　 set 字段名1=@字段名1，字段名2=字段名2 where id=id";

    tableName = "abcd";

    //获取属性
    var ps = t.GetProperties();
    ps.ToList().ForEach(p =>
    {
        if (!p.Name.ToLower().Equals("id"))
        {
            var v = p.GetValue(entity);
            if (v != null)
            {
                //字段名1=字段值1,字段名2=字段值2
                filedValue += $"{p.Name} = @{p.Name},";
            }
        }
    });
    sql = $"update {tableName}　 set {filedValue.TrimEnd(',')} where id=@id";
    Console.WriteLine(sql);
}

void TestReflection()
{
    //获取UserModel这个类的具体类型
    var t = typeof(UserModel);

    //六大方法
    //方法、属性、成员、构造、字段、事件


    //1、构造函数
    //var cots = t.GetConstructors();
    //cots.ToList().ForEach(c => {
    //    Console.WriteLine(c.Name);
    //});

    //2、所有成员
    //var ms = t.GetMembers();
    //foreach (var m in ms)
    //{
    //    Console.WriteLine(m.Name);
    //}

    //3、所有方法
    //var mt = t.GetMethods();
    //foreach (var m in mt)
    //{
    //    Console.WriteLine(m.Name);
    //    //if (m.Name.ToLower().Equals("testvalue"))
    //    //{
    //    //    var e = t.GetMethod(m.Name);
    //    //    e.Invoke(null, null);
    //    //}
    //}

    //4、事件
    //var es = t.GetEvents();
    ////事件和委托：event,
    ////委托：四种（一个自定义，三个系统自带）
    ////delegate
    ////Func<>
    ////Action<>
    ////Predicate<>
    //foreach (var item in es)
    //{
    //    Console.WriteLine(item.Name);
    //}

    //5、获取字段
    //var fs = t.GetFields();
    //foreach (var f in fs)
    //{
    //    Console.WriteLine(f.Name);
    //}
    //Console.WriteLine("---------------------");

    //6、获取属性 -----就是我们需要的，可以用来拼接sql
    //var ps = t.GetProperties();
    //foreach (var p in ps)
    //{
    //    Console.WriteLine(p.Name);
    //}
}

#endregion



string GetTableName<T>()
{
    var tableName = "";
    var t = typeof(T);
    var obj = t.GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.Schema.TableAttribute), true);

    if (obj != null && obj.Length > 0)
    {
        tableName = ((System.ComponentModel.DataAnnotations.Schema.TableAttribute)obj[0]).Name;
    }
    else
    {
        tableName = t.Name;
    }
    return tableName;
}


/*
 * 单例：服务器只有这个对象的一个实体
 * 懒汉和饿汉
 * **/

public class FactorySingle
{
    private static CreateCarFactory _factory;

    private static object _obj;
    public static CreateCarFactory GetFactory()
    {
        lock (_obj)
        {
            if (_factory == null)
                return new CreateCarFactory();

            return _factory;

        }
    }
}


/*
 * 有一家组装汽车的工厂
 * 只能组装三种牌子：宝马、奥迪、奔驰
 * **/


//组装汽车工厂
public class CreateCarFactory
{
    //开始组装
    public ICar Create(string type)
    {
        if (type == "宝马")
        {
            return new BMWCar();
        }
        else if (type == "奔驰")
        {
            return new BCCar();
        }
        else if (type == "奥迪")
        {
            return new ADCar();
        }
        else
        {
            return null;
        }
    }
}


public interface ICar
{
    void Run();
}

//宝马车
public class BMWCar : ICar
{
    public void Run()
    {
        Console.WriteLine("我是宝马，能跑120km/h");
    }
}

//奔驰
public class BCCar : ICar
{
    public void Run()
    {
        Console.WriteLine("我是奔驰，能跑130km/h");
    }
}


//奥迪
public class ADCar : ICar
{
    public void Run()
    {
        Console.WriteLine("我是奥迪，能跑150km/h");
    }
}